﻿using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

namespace Helpers
{
    public class CasHelper
    {
#if DEBUG
        static string _casUrl = "http://192.168.40.138:8080/cas";
#else 
        static string _casUrl = "http://sso.xx.com/cas";
#endif
        public static async Task<string> GetCasUrlAsync(string service, string username, string password)
        {
            service = await GetCasCoreService(service);
            //var input = new { username, password, service = WebUtility.UrlEncode(service) };
            var input = new Dictionary<string, string> { { "username", username }, { "password", password }, { "service", WebUtility.UrlEncode(service) } };
            var st = await RunAsync("/v1/tickets", input, true);
            var op = service.IndexOf("?") != -1 ? "&" : "?";
            if (string.IsNullOrEmpty(st))
            {
                return service + op + "ticket=";
            }
            var ticket = await RunAsync(st.Replace(_casUrl, ""), new Dictionary<string, string> { { "service", service } });
            return service + op + "ticket=" + ticket;
        }
        private static async Task<string> RunAsync(string url, IDictionary<string, string> input, bool isLocation = false)
        {
            var pramater = new List<KeyValuePair<string, string>>();
            if (input != null)
            {
                foreach (var item in input)
                {
                    pramater.Add(new KeyValuePair<string, string>(item.Key, item.Value));
                }
            }
            var content = new FormUrlEncodedContent(pramater);
            var r = await new HttpClient().PostAsync(_casUrl + url, content);
            if (isLocation)
            {
                return r.Headers.Location?.ToString() ?? "";
            }
            var result = await r.Content.ReadAsStringAsync();
            return result;
        }
        /// <summary>
        /// 兼容core版本CAS登录页面的sigin-cas参数
        /// </summary>
        /// <param name="service">client地址</param>
        /// <returns></returns>
        private static async Task<string> GetCasCoreService(string service)
        {
            var key = "service=";
            var r = await new HttpClient().GetAsync(service);
            var url = r.RequestMessage.RequestUri.AbsoluteUri;
            url = WebUtility.UrlDecode(url.Substring(url.IndexOf(key) + key.Length));
            return url;
        }

    }
}
